package top.leoseven.adminproject.presenter;

import android.content.Context;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.PostRequest;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Response;
import top.leoseven.adminproject.R;
import top.leoseven.adminproject.modle.AppInfo;
import top.leoseven.adminproject.modle.StuHomeWorkInfo;
import top.leoseven.adminproject.service.StuHomeWorkService;
import top.leoseven.adminproject.view.StuHomeWorkList;

/**
 * Created by admin2 on 2018/4/11.
 */

public class StuHomeWorkPresenter {
    private StuHomeWorkService service;
    private Context context;
    public void init(StuHomeWorkService service, Context context){
        this.service=service;
        this.context=context;
    }
    public void load(int id,int type){
        PostRequest params = OkHttpUtils.post(AppInfo.SERVER+context.getString(R.string.showHomeWorkList))
                .params("teacherid", AppInfo.getUserid());
        if (type== StuHomeWorkList.selectByHomeWorkID) {
            params.params("type",type)
                    .params("workid",id).execute(new HomeWorkCallBack());
        }else if (type==StuHomeWorkList.selectByKechengID){
            params.params("type",type)
                    .params("kechengid",id)
                    .execute(new HomeWorkCallBack());
        }

    }
    public void load(String stuid){
        OkHttpUtils.post(AppInfo.SERVER+context.getString(R.string.showHomeWorkList))
                .params("teacherid", AppInfo.getUserid())
                .params("type",StuHomeWorkList.selectByStuID)
                .params("stuid",stuid)
                .execute(new HomeWorkCallBack());
    }
    class HomeWorkCallBack extends StringCallback{

        @Override
        public void onSuccess(String s, Call call, Response response) {
            JSONObject root = JSON.parseObject(s);
            if (root.getIntValue("code")==200) {
                ArrayList<StuHomeWorkInfo> infos = new ArrayList<>();
                JSONArray data = root.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    infos.add(data.getObject(i,StuHomeWorkInfo.class));
                }
                service.onSuccess(infos);
            }
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            service.onError(e.getMessage());
        }
    }
}
